package com.example.ftp.Controller;


import com.example.ftp.Beans.Site;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.io.*;
import java.util.Arrays;
import java.util.List;



public class SiteManagerController {
    /**
     * 站点列表
     */
    ObservableList<Site> siteList = FXCollections.observableArrayList();

    public void SiteManagerDao() {
        this.Deserialization();
    }

    /**
     * 新增站点
     */
    public void AddSite(Site newSite) {
        siteList.add(newSite);
        this.Serialization();
        this.Deserialization();
    }

    /**
     * 根据ip和端口删除站点
     */
    public boolean DeleteSite(String ip, String port) {
        boolean is = false;
        for(int i = 0; i < siteList.size();i++) {
            if(siteList.get(i).getIp().equals(ip)&&siteList.get(i).getPort()==Integer.parseInt(port)) {
                siteList.remove(i);
                is = true;
                this.Serialization();
                this.Deserialization();
                break;
            }
        }
        return is;
    }

    /**
     * 序列化 将站点列表序列化进文件
     */
    public void Serialization() {
        File file = new File("site.Bin");
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))){
            Site[] obj = new Site[siteList.size()];
            siteList.toArray(obj);
            out.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化 将站点列表从文件读取出来
     */
    public void Deserialization() {
        siteList.clear();
        File file = new File("site.Bin");
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
            Site[] obj = (Site[]) in.readObject();
            List<Site> List = Arrays.asList(obj);
            for (Site site : List) {
//                System.out.println(List.get(i).getIp()+" "+
//                        List.get(i).getPort()+" "+
//                        List.get(i).getName()+" "+
//                        List.get(i).getPassword());
                Site newSite = new Site(site.getName(), site.getIp(), site.getPort(), site.getUserName(), site.getPassword(), site.getNote());
                siteList.add(newSite);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取站点列表
     * @return 站点列表
     */
    public ObservableList<Site> getSiteList() {
        return siteList;
    }
}
